#include "GenerateAlarmImage.h"
#include "Utils/Common.h"
#include "Utils/Log.h"

namespace AVSAnalyzer {
    
GenerateAlarmImage::GenerateAlarmImage(const std::string& code, const std::string& controlCode, const Config& config) 
    : mCode(code)
    , mControlCode(controlCode)
    , mLastImageSaveTime(0)
    , mAlarmDir(config.uploadDir + "/alarm_images") {
    
    // 确保报警图片保存目录存在
    if (!std::filesystem::exists(mAlarmDir)) {
        std::filesystem::create_directories(mAlarmDir);
    }
}

GenerateAlarmImage::~GenerateAlarmImage() {
}

bool GenerateAlarmImage::saveAlarmImage(const cv::Mat& image, float score) {
    int64_t currentTime = getCurTimestamp();
    // 检查是否满足保存间隔要求
    if (currentTime - mLastImageSaveTime < IMAGE_SAVE_INTERVAL) {
        return false;
    }

    // 检查与上次保存的图片是否过于相似
    if (!mLastSavedImage.empty() && isSimilarImage(image, mLastSavedImage)) {
        LOGI("saveAlarmImage: image is similar to last saved image, skip saving");
        return false;
    }

    // 生成文件名并保存图片
    std::string filename = generateFilename(score);
    bool success = cv::imwrite(filename, image);
    
    if (success) {
        mLastImageSaveTime = currentTime;
        image.copyTo(mLastSavedImage);
    }
    
    return success;
}

bool GenerateAlarmImage::isSimilarImage(const cv::Mat& img1, const cv::Mat& img2, float threshold) {
    if (img1.empty() || img2.empty()) return false;
    
    // 转换为灰度图
    cv::Mat gray1, gray2;
    cv::cvtColor(img1, gray1, cv::COLOR_BGR2GRAY);
    cv::cvtColor(img2, gray2, cv::COLOR_BGR2GRAY);
    
    // 计算直方图
    cv::Mat hist1, hist2;
    int channels[] = {0};
    int histSize[] = {256};
    float range[] = {0, 256};
    const float* ranges[] = {range};
    
    cv::calcHist(&gray1, 1, channels, cv::Mat(), hist1, 1, histSize, ranges);
    cv::calcHist(&gray2, 1, channels, cv::Mat(), hist2, 1, histSize, ranges);
    
    // 归一化直方图
    cv::normalize(hist1, hist1, 0, 1, cv::NORM_MINMAX);
    cv::normalize(hist2, hist2, 0, 1, cv::NORM_MINMAX);
    
    // 计算相似度
    double similarity = cv::compareHist(hist1, hist2, cv::HISTCMP_CORREL);
    return similarity > threshold;
}

std::string GenerateAlarmImage::generateFilename(float score) {
    // 获取当前时间并格式化
    auto now = std::chrono::system_clock::now();
    auto now_time = std::chrono::system_clock::to_time_t(now);
    std::stringstream ss;
    ss << std::put_time(std::localtime(&now_time), "%Y%m%d_%H%M%S");
    
    // 生成文件名格式: alarm_images/设备编号_控制通道_时间_分数.jpg
    return mAlarmDir + "/" + mCode + "_" + mControlCode + "_" + 
           ss.str() + "_" + 
           std::to_string(score).substr(0,4) + ".jpg";
}

} 